'use strict';
const db = uniCloud.database();
const dbCmd = db.command;
const $ = dbCmd.aggregate;
exports.main = async (event, context) => {
	/* let s=await db.collection('wmz-entitlement-balance').where({
		type:"支出"
	}).remove()
	console.log(s)
	return */
	let rechargeDatas = await db.collection('wmz-entitlement-order').where({
		deductio_status: dbCmd.exists(false),
		status:'已付款'
	}).limit(100).orderBy('create_time', 'desc').get()
	rechargeDatas = rechargeDatas.data
	console.log(rechargeDatas.length)
	let appletInfo
	for (var i in rechargeDatas) {
		appletInfo = await db.collection('wmz-applet-info').doc(rechargeDatas[i].app_id).get()
		appletInfo = appletInfo.data[0]
		if (appletInfo) {
			let balance = appletInfo.balance
			if (balance) {
				let msg_deductio = 0.1
				if (appletInfo.msg_deductio) {
					msg_deductio = appletInfo.msg_deductio
				}
				let entitlement_deductio = 1.1
				if (appletInfo.entitlement_deductio) {
					entitlement_deductio = appletInfo.entitlement_deductio
				}
				balance = (balance - msg_deductio - entitlement_deductio).toFixed(2)
				await db.collection('wmz-applet-info').doc(rechargeDatas[i].app_id).update({
					balance: balance
				})
				await db.collection('wmz-entitlement-balance').add({
					app_id: rechargeDatas[i].app_id,
					shop_id: rechargeDatas[i].app_id,
					create_time: rechargeDatas[i].pay_time,
					money: msg_deductio,
					name: "短信费用",
					type: "支出",
					way: "短信",
					trade_no: rechargeDatas[i].trade_no
				})
				await db.collection('wmz-entitlement-balance').add({
					app_id: rechargeDatas[i].app_id,
					shop_id: rechargeDatas[i].app_id,
					create_time: rechargeDatas[i].pay_time,
					money: entitlement_deductio,
					name: "权益卡购买费用",
					type: "支出",
					way: "权益卡",
					trade_no: rechargeDatas[i].trade_no
				})
				
				await db.collection('wmz-entitlement-order').doc(rechargeDatas[i]._id).update({
					deductio_status: true
				})
			}
		}
	}
	return event
};